<template>
  <div class="home_container">
    <!-- 首页 -->
    <div class="home_lt relative">
      <div class="home_lt_top">
        <el-card class="top_card">
          <template #header>
            <div class="w-full flex">
              <el-tag type="primary" class="tag_title">总览</el-tag>
              <el-select
                v-model="selectForm.saleTimeId"
                size="small"
                filterable
                class="all-select"
                @change="changeSaleTimeId"
              >
                <el-option label="今天" :value="1" />
                <el-option label="昨天" :value="2" />
                <el-option label="本周" :value="3" />
                <el-option label="上周" :value="4" />
                <el-option label="本月" :value="5" />
                <el-option label="上月" :value="6" />
                <el-option label="今年" :value="7" />
              </el-select>
            </div>
          </template>
          <sale ref="saleRef" />
        </el-card>
        <el-card class="top_card">
          <CalendarPage />
        </el-card>
      </div>
      <div class="home_lt_center">
        <el-card class="center_card">
          <template #header>
            <div class="w-full flex">
              <el-tag type="primary" class="tag_title">客户</el-tag>
              <el-select
                v-model="selectForm.customerTimeId"
                size="small"
                filterable
                class="all-select"
                @change="getCustomerEchartsList"
              >
                <el-option label="近一周" :value="1" />
                <el-option label="近一个月" :value="2" />
                <el-option label="近三个月" :value="3" />
                <el-option label="近半年" :value="4" />
                <el-option label="近一年" :value="5" />
                <el-option label="近三年" :value="6" />
              </el-select>
              <el-select
                v-model="selectForm.customerTypeId"
                size="small"
                filterable
                class="all-select"
                @change="getCustomerEchartsList"
              >
                <el-option label="按订单" :value="1" />
                <el-option label="按商品" :value="2" />
                <el-option label="按金额" :value="3" />
              </el-select>
            </div>
          </template>
          <BaseChart
            :data="customerData"
            :xAxis="customerTime"
            type="bar"
            :barWidth="12"
            height="26vh"
            :direction="2"
          />
        </el-card>
        <el-card class="center_card">
          <template #header>
            <div class="w-full flex justify-between items-center">
              <div class="w-full flex">
                <el-tag type="primary" class="tag_title">商品</el-tag>
                <el-select
                  v-model="selectForm.productTimeId"
                  size="small"
                  filterable
                  class="all-select"
                  @change="getProductEchartsList"
                >
                  <el-option label="近一周" :value="1" />
                  <el-option label="近一个月" :value="2" />
                  <el-option label="近三个月" :value="3" />
                  <el-option label="近半年" :value="4" />
                  <el-option label="近一年" :value="5" />
                  <el-option label="近三年" :value="6" />
                </el-select>
              </div>
              <el-button
                size="small"
                class="w-[4rem]"
                icon="RefreshRight"
                @click="resetProduct"
              >
                重置
              </el-button>
            </div>
          </template>
          <ChartProduction
            :data="productData"
            :xAxis="productTime"
            type="bar"
            :barWidth="10"
            height="26vh"
            :direction="2"
            :isClick="true"
            @chart-click="handleChartClick"
          />
        </el-card>
      </div>
      <el-card class="home_lt_bottom">
        <template #header>
          <div class="w-full flex">
            <el-tag type="primary" class="tag_title">交易趋势</el-tag>
            <el-select
              v-model="selectForm.trendTimeId"
              size="small"
              filterable
              class="all-select"
              @change="getTrendEchartsList"
            >
              <el-option label="近一周" :value="1" />
              <el-option label="近一个月" :value="2" />
              <el-option label="近三个月" :value="3" />
              <el-option label="近半年" :value="4" />
              <el-option label="近一年" :value="5" />
              <el-option label="近三年" :value="6" />
            </el-select>
            <el-select
              v-model="selectForm.trendTypeId"
              size="small"
              filterable
              class="all-select"
              @change="getTrendEchartsList"
            >
              <el-option label="按订单" :value="1" />
              <el-option label="按商品" :value="2" />
              <el-option label="按金额" :value="3" />
            </el-select>
            <el-button
              class="ml-2"
              size="small"
              @click="getTrendEchartsList(1)"
            >
              {{ selectForm.type == "bar" ? "折线图" : "柱状图" }}
            </el-button>
          </div>
        </template>
        <BaseChart
          :data="trendData"
          :xAxis="trendTime"
          :type="selectForm.type"
          :barWidth="20"
          height="28vh"
          :direction="1"
        />
      </el-card>

      <CheckInfo class="flow_page" v-if="cutStatus == 2" />
    </div>
    <div class="home_gt">
      <UseMobile class="h-[25%]" />

      <div class="h-[74%] flex flex-col justify-between">
        <el-card class="h-[7%] min-h-[2rem]">
          <div class="w-full h-[1.6rem] flex items-center">
            <el-tag type="info" class="w-[3rem] text-[0.6rem]">自助扫码</el-tag>
            <el-button
              type="primary"
              link
              class="text-[0.7rem] px-[0.1rem]"
              @click="click_qr_look"
            >
              <el-icon><View /></el-icon>
              预览
            </el-button>

            <el-button
              type="warning"
              link
              class="text-[0.7rem]"
              @click="handleDownload"
            >
              <el-icon><Download /></el-icon>
              下载
            </el-button>
          </div>
        </el-card>

        <el-card
          class="h-[91%]"
          v-loading="check_loading"
          element-loading-text="加载中..."
          element-loading-background="rgba(122, 122, 122, 0.8)"
        >
          <template #header>
            <div class="w-full flex">
              <el-tag type="primary" class="tag_title">检查</el-tag>
              <el-select
                v-model="selectForm.checkTimeId"
                size="small"
                filterable
                class="all-select"
                @change="handleRefreshCheckList"
              >
                <el-option label="今天" :value="1" />
                <el-option label="本周" :value="2" />
                <el-option label="本月" :value="3" />
              </el-select>
            </div>
          </template>
          <el-input
            v-model="selectForm.code"
            placeholder="姓名/手机号搜索"
            clearable
            size="small"
            class="w-full"
            @clear="handleRefreshCheckList"
          >
            <template #append>
              <el-icon class="cursor-pointer" @click="handleRefreshCheckList">
                <Search />
              </el-icon>
            </template>
          </el-input>

          <AllCheck
            :loading="check_loading"
            ref="allCheckRef"
            @handleBack="handleDefaultCheck"
          />
        </el-card>
      </div>
    </div>

    <el-dialog v-model="qr_dialog" :width="600" top="25vh">
      <div class="w-full flex justify-center">
        <el-image :src="qrCode" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { debounce } from "lodash";
import sale from "./component/sale.vue";
import CalendarPage from "./component/CalendarPage.vue";
import UseMobile from "./component/UseMobile.vue";
import BaseChart from "@/components/baseChart.vue";
import ChartProduction from "@/components/ChartProduction.vue";
import AllCheck from "./component/AllCheck.vue";
import CheckInfo from "./component/CheckInfo.vue";

import { handleApiResponse } from "@/utils/request.js";
import {
  GetGlassStoreShipCustomerDistribution,
  GetGlassStoreShipGoodsDistribution,
  GetGlassStoreShipTrend,
  GetCheckOrderQrCode,
} from "../../../../wailsjs/go/api/HomeApi";

onMounted(() => {
  getCustomerEchartsList();
  getProductEchartsList();
  getTrendEchartsList();
  getQr();
});

const userStore = useUserStore();
const { cutStatus, flowActiveIndex, checkDetailForm } = storeToRefs(userStore);

const selectForm = ref({
  saleTimeId: 1,
  customerTimeId: 1,
  customerTypeId: 1,
  productTimeId: 1,
  productTypeId: 1,
  trendTimeId: 1,
  trendTypeId: 1,
  checkTimeId: 1,
  code: "",
  type: "bar", // 图表类型 默认柱状图 bar-柱状图, line-折线图
});

const allCheckRef = ref(null);
const check_loading = ref(false);
const handleRefreshCheckList = () => {
  // check_loading.value = true;
  allCheckRef.value?.getList({
    code: selectForm.value.code,
    timeType: selectForm.value.checkTimeId,
  });
};
const handleDefaultCheck = (val) => {
  check_loading.value = val;
};

// 1.销售总览
const saleRef = ref(null);
const changeSaleTimeId = () => {
  saleRef.value.getSaleData(selectForm.value.saleTimeId);
};

// 2.客户总览
const customerTime = ref([]);
const customerData = ref([]);
async function getCustomerEchartsList() {
  handleApiResponse(() =>
    GetGlassStoreShipCustomerDistribution({
      typeId: selectForm.value.customerTypeId,
      timeFlag: selectForm.value.customerTimeId,
    })
  ).then((res) => {
    if (res.code == 0) {
      customerTime.value = [];
      customerData.value = [];

      let list = res.data.list || [];

      list.forEach((item) => {
        customerTime.value.push(item.name + "岁");
        customerData.value.push(
          selectForm.value.customerTypeId == 3 ? item.count / 100 : item.count
        );
      });
    }
  });
}

// 3.商品总览
const productTime = ref([]);
const productData = ref([]);
async function getProductEchartsList(gId, name, type) {
  if (type) {
    selectForm.value.productTimeId = 1;
    selectForm.value.productTypeId = 1;
  }

  handleApiResponse(() =>
    GetGlassStoreShipGoodsDistribution({
      timeFlag: selectForm.value.productTimeId,
      typeId: selectForm.value.productTypeId,
      generalId: gId,
      name: name,
    })
  ).then((res) => {
    if (res.code == 0) {
      // console.log(res);
      productTime.value = [];
      productData.value = [];
      let list = res.data.list || [];

      list.forEach((item) => {
        productTime.value.push(item.name);
        productData.value.push({
          value: item.count,
          id: item.id,
          name: item.name,
        });
      });
    }
  });
}

let generalId = ref(null);
let _name = ref("");

const handleChartClick = (val) => {
  if (selectForm.value.productTypeId >= 4) return;

  selectForm.value.productTypeId += 1;

  if (selectForm.value.productTypeId == 2) {
    generalId.value = val.id;
  }

  if (selectForm.value.productTypeId <= 4) {
    _name.value = val.name;
  }

  getProductEchartsList(generalId.value, _name.value);
};
// 重置商品
const resetProduct = () => {
  selectForm.value.productTimeId = 1;
  selectForm.value.productTypeId = 1;
  getProductEchartsList(null, "");
};

// 4.交易趋势
const trendTime = ref([]);
const trendData = ref([]);
async function getTrendEchartsList(a) {
  if (a) {
    selectForm.value.type = selectForm.value.type == "bar" ? "line" : "bar";
  }
  trendTime.value = [];
  trendData.value = [];
  handleApiResponse(() =>
    GetGlassStoreShipTrend({
      timeFlag: selectForm.value.trendTimeId,
      typeId: selectForm.value.trendTypeId,
    })
  ).then((res) => {
    if (res.code == 0) {
      let list = res.data.list || [];
      for (const key in list) {
        trendTime.value.push(key);
        trendData.value.push(
          selectForm.value.trendTypeId == 3 ? +list[key] / 100 : +list[key]
        );
      }
    }
  });
}

// 5.自助扫码
const qr_dialog = ref(false);
const qrCode = ref("");
const getQr = () => {
  handleApiResponse(() => GetCheckOrderQrCode()).then((res) => {
    if (res.code == 0) {
      qrCode.value = res.data.qrCodeUrl || "";
    }
  });
};

// 预览
const click_qr_look = () => {
  qr_dialog.value = true;
};

// 下载图片的函数
const downloadImage = () => {
  if (qrCode.value) {
    // 创建一个新的 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest();
    xhr.open("GET", qrCode.value, true);
    xhr.responseType = "blob";

    xhr.onload = function () {
      if (xhr.status === 200) {
        const blob = xhr.response;
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = "扫码自助开单二维码.png"; // 下载的文件名
        a.click();
        // 释放生成的 URL
        URL.revokeObjectURL(a.href);
      }
    };
    xhr.send();
  } else {
    // ElMessage.warning(imgUrlForm.value.errMsg);
    qr_dialog.value = true;
  }
};

// 下载
const handleDownload = debounce(downloadImage, 300);
</script>

<style scoped lang="scss">
.home_container {
  height: calc(100vh - 7rem);
  @apply w-full flex justify-between;

  .tag_title {
    @apply text-[0.7rem] font-normal;
  }

  .home_lt {
    @apply w-[79.5%] h-full flex flex-col justify-between items-center;

    .home_lt_top {
      @apply w-full h-[25%] flex  justify-between items-center;

      .top_card {
        @apply w-[49.5%] h-full;
      }
    }

    .home_lt_center {
      @apply w-full h-[35%] flex justify-between items-center;
      .center_card {
        @apply w-[49.5%] h-full;
      }
    }

    .home_lt_bottom {
      @apply w-full h-[38%];
    }
  }

  .home_gt {
    @apply w-[20%] min-w-[10rem] h-full flex flex-col justify-between;
  }

  .el-button + .el-button {
    @apply ml-1;
  }
}

.all-select {
  @apply w-[5rem] ml-2;
}

.home_container :deep(.el-card__header) {
  padding: 0.2rem 0.3rem !important;
}
.home_container :deep(.el-card__body) {
  padding: 0.2rem 0.3rem !important;
}

.flow_page {
  @apply w-full h-full bg-[#f1f0f0] absolute top-0 left-0 z-[999] flex justify-between;
}
</style>